import { DataSource } from "maishu-wuzhui";
import { ItemDialog } from "./item-dialog";
import React = require("react");
import ReactDOM = require("react-dom");

export async function dropdown<T>(options: {
    element: HTMLElement,
    dataSource: DataSource<T>,
    textField: keyof T, valueField: keyof T, emptyText?: string,
    name?: string
    value?: string
    addDialog?: DropdownDialog["props"],
    onChanged?: (item: T) => void;
}) {

    class SelectElement extends React.Component<{ value: string }, { items: T[], value: string }> {
        constructor(props) {
            super(props);

            this.state = { items: [], value: this.props.value };
        }

        async componentDidMount() {
            let r = await options.dataSource.executeSelect({});
            this.setState({ items: r.dataItems });
            // options.dataSource.inserted.add((sender, item) => {
            //     let { items } = this.state;
            //     items.push(item);
            //     this.setState({ items });
            //     // this.setState({ items, value: `${item[options.valueField]}` })
            // })
            // options.dataSource.updated.add((sender, item) => {
            //     console.assert(item[options.valueField]);
            //     let { items } = this.state;
            //     let o = items.filter(c => c[options.valueField] == item[options.valueField])[0];
            //     console.assert(o);
            //     Object.assign(o, item);
            //     this.setState({ items });
            // })
            // options.dataSource.deleted.add((sender, item) => {
            //     let { items } = this.state;
            //     items = items.filter(c => c[options.valueField] != item[options.valueField]);
            //     this.setState({ items });
            // })
        }

        render() {
            let { items, value } = this.state;
            value = value || "";
            return <select name={options.name} className="form-control"
                ref={e => {
                    if (!e) return;

                    if (value)
                        e.value = value;

                    e.onchange = () => {
                        if (options.onChanged) {
                            let item = items.filter(o => `${o[options.valueField]}` == e.value)[0];
                            options.onChanged(item);
                        }
                    }
                }}>
                {options.emptyText ? <option>{options.emptyText}</option> : null}
                {items.map(o =>
                    <option key={`${o[options.valueField]}`} value={`${o[options.valueField]}`}
                        data-value-type={typeof o[options.valueField]}>
                        {o[options.textField]}
                    </option>
                )}
            </select>
        }
    }

    if (options.addDialog == null) {
        ReactDOM.render(<SelectElement value={options.value} />, options.element);
        return;
    }

    // let element = document.createElement("div");
    options.element.className = "input-group";
    let dropdownDialog: DropdownDialog;
    let selectElement: SelectElement;
    ReactDOM.render(<>
        <SelectElement value={options.value} ref={e => selectElement = e || selectElement} />
        <span className="input-group-btn">
            <button className="btn btn-default" type="button"
                onClick={() => dropdownDialog.show(`添加${options.addDialog.label}`,
                    async (a) => {
                        let item: T = {} as T;
                        item[options.textField] = a.name as any;
                        let executeResult = await options.dataSource.insert(item);
                        let items = selectElement.state.items;
                        items.push(item);
                        selectElement.setState({ items, value: `${item[options.valueField]}` });
                        if (options.onChanged) {
                            options.onChanged(item);
                        }
                        Object.assign(item, executeResult);
                    })}>
                <i className="icon-plus"></i>
            </button>
        </span>
        <DropdownDialog ref={e => dropdownDialog = e || dropdownDialog} {...options.addDialog} />
        {/* {ReactDOM.createPortal(<DropdownDialog ref={e => dropdownDialog = e || dropdownDialog} {...options.addDialog} />, args.page.element)} */}
    </>, options.element)
}

class DropdownDialog extends ItemDialog<{ label: string, placeholder: string }, { name: string }> {
    render() {
        let item = this.state.item;
        return <div className="form-horizontal">
            <div className="form-group">
                <label className="control-label col-sm-2">{this.props.label}</label>
                <div className="col-sm-10">
                    <input name="sortNumber" className="form-control"
                        placeholder={this.props.placeholder} value={item.name || ""}
                        onChange={e => {
                            item.name = e.target.value;
                            this.setState({ item });
                        }} />
                </div>
            </div>
        </div>
    }
}


